package com.tianji.learning.listener;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.tianji.common.constants.CacheConstant;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.domain.dto.PointMsgDTO;
import com.tianji.learning.domain.po.PointsRecord;
import com.tianji.learning.enums.PointsRecordType;
import com.tianji.learning.mapper.PointsRecordMapper;
import com.tianji.learning.service.IPointsRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
public class PointListener {

    @Autowired
    private IPointsRecordService pointService;
    @Autowired
    private PointsRecordMapper pointsRecordMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value=@Queue(name=MqConstants.Queue.SIGN_POINTS_QUEUE),
            exchange = @Exchange(name=MqConstants.Exchange.LEARNING_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.SIGN_IN
    ))
    public void onPoint(PointMsgDTO msg){
        // 用户当天已经获得的积分（区分渠道）
        // select sum(points) where userId = #{userId} and type= #{type} and create_time between and
        PointsRecordType recordType = PointsRecordType.SIGN;
        int type = recordType.getValue();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime begin = LocalDateTimeUtil.beginOfDay(now);
        LocalDateTime end = LocalDateTimeUtil.endOfDay(now);
        int oldPoints = pointsRecordMapper.sumUserPoints(msg.getUserId(), type, begin, end);
        int maxPoints = recordType.getMaxPoints();
        int points = 0;
        // 如果有最大积分的限制
        if(maxPoints > 0){
            if(oldPoints >= maxPoints){
                log.info("已经超过最大值");
                return;
            }
            points = Math.min(maxPoints - oldPoints, msg.getPoints());
        }else{
            // 如果没有限制
            points = msg.getPoints();
        }
        PointsRecord pointsRecord = new PointsRecord();
        pointsRecord.setUserId(msg.getUserId());
        pointsRecord.setType(type);
        pointsRecord.setPoints(points);
        pointsRecord.setCreateTime(LocalDateTime.now());
        pointService.save(pointsRecord);
        String yyyyMM = LocalDateTimeUtil.format(LocalDateTime.now(), "yyyyMM");
        String key = CacheConstant.POINTS_BOARD+ yyyyMM;
        redisTemplate.opsForZSet().incrementScore(key, ""+msg.getUserId(), points);
    }

}